class Article < ActiveRecord::Base
  belongs_to :user
  belongs_to :lough
    
  validates_presence_of :title, :lough_id, :user_id
  
  before_save :strip_all_html
    
  # Finds all articles by date using pagination help.
  def self.find_pagination_by_date(year, month = nil, day = nil, page = 1)
  	if !year.blank?
      from, to = self.time_delta(year, month, day)
      find_pagination_published(:conditions => ["published_at BETWEEN ? AND ?",
                                          from, to], :page => page)
	else
	  find_pagination_published(:page => page)
  	end
  end
  
  def self.find_recent_published(limit)
  	find(:all, :order => default_order, :limit => limit)
  end
  
  cattr_accessor :per_page
  
  def self.per_page=(pp)
  	@@per_page = pp
  end
  
  def self.per_page
  	@@per_page ||= 20 # Set default value to 20
  end
  
  def self.strip_html(str, allow = [], add_space = false, replace_entities = false)
	if str
	  str = str.strip || ''
	  allow_arr = allow.join('|') << '|\/'
	  str = str.gsub(/<(\/|\s)*[^(#{allow_arr})][^>]*>/, (add_space ? ' ' : ''))
	  if replace_entities
	    str = str.
	      gsub('&#8211;', ' - ').   # en-dash
      gsub('&#8212;', ' -- ').  # em-dash
      gsub('&mdash;', ' -- ').  # em-dash
      gsub('&#8216;', "'").     # open single quote
      gsub('&#8217;', "'").     # close single quote
      gsub('&#8220;', '"').     # open double quote
      gsub('&#8221;', '"').     # close double quote
      gsub('&#8230;', ' ... '). # ellipsis
      gsub('&amp;',   '&').     # ampersand
      gsub('&quot;',  '"').     # quote
      gsub('&#039;',  "'").     # apos
      gsub('&lt;',    ' < ').   # less than
      gsub('&gt;',    ' > ').   # greater than
      gsub(/[ ]+/,    ' ')
        return str.strip
      else
        return str
      end
	end
  end
  
  def self.replace_html_bracket(str)
  	if str
  	  str = str.gsub('<','&lt;').   # less than
      gsub('>','&gt;')   # greater than
      return str
    else
	  return str
  	end
  end
  
  protected
  
  def strip_all_html
    write_attribute 'body', Article.strip_html(read_attribute('body_html'))
    write_attribute 'title', Article.replace_html_bracket(read_attribute('title'))
  end
  
  # Symbol :all is not need.
  def self.find_pagination_published(options = {})
  	default_options = {:order => default_order, :conditions => {:published => true}}
  	options = default_options.merge(options)
    paginate options
  end
  
  def self.default_order
  	'published_at DESC'
  end
  
  def self.time_delta(year, month = nil, day = nil)
    from = Time.mktime(year, month || 1, day || 1)

    to = from.next_year
    to = from.next_month unless month.blank?
    to = from + 1.day unless day.blank?
    to = to - 1 # pull off 1 second so we don't overlap onto the next day
    return [from, to]
  end
end
